/**
 * 
 * @author: yurfer (github.com/yurfer)
 * @date 2018-10-18 09:56:03
 * @version 1.0
 */

/*This component is a set of Comfirm component which in Ant Design*/
/*说明*/
/*整合表单组件,
统一入口,使用对象数组的形式,配置如:组件数量,组件类型,组件关联value的属性名,组件样式,组件事件等等的内容
统一出口,使用对象的形式,键名为组件关联value的属性名,键值为组件对应的值
*重置时,统一返回值,类型为String的,返回"",类型为对象的,返回{},类型为数组的,返回[]
*/
import React, { PureComponent } from 'react';
import moment from 'moment';
import {
	Row,
	Col,
	Card,
	Tabs,
	Form,
	Icon,
	Modal,
	Table,
	Input,
	Upload,
	Select,
	Button,
	message,
	DatePicker,
	Popconfirm,
} from 'antd';
import token from '../../utils/token';
import {env, host} from '../../utils/request'

function buildAuthorization() {
  let tokenVal = token.get();
  return (token !== '') ? tokenVal : '';
}

const FormItem = Form.Item;
const { Option } = Select;
const RangePicker = DatePicker.RangePicker;
const { TextArea } = Input;
const Dragger = Upload.Dragger;

@Form.create()
export default class GeneralFilterComponent extends PureComponent {
	state = {
		upload: {
			url: '',
			fresh: false,
		},
	};

	componentDidMount() {};

	handleFormCancel = () => {
		const { upload } = this.state;
		const { form, onCancel } = this.props;
		form.validateFields((err, fieldsValue) => {
			for (let [_key, _val] of Object.entries(fieldsValue)) {
				if (!_val && _val != 0 && typeof(_val) != 'object') {
					fieldsValue[_key] = '';
				}
			}
			upload.fresh = false;
			form.resetFields();
			this.setState({
				upload: {
					url: '',
					fresh: false,
				}
			})
			onCancel(fieldsValue)
			if (err) return;
		});
	};

	handleComfirm = () => {
		const { form, onSubmit } = this.props;
		form.validateFields((err, fieldsValue) => {
			for (let [_key, _val] of Object.entries(fieldsValue)) {
				if (!_val && _val != 0) {
					fieldsValue[_key] = '';
				}
			}
			onSubmit(fieldsValue, err);
			if (err) {
				return;
			} else {
				form.resetFields();
				this.setState({
					upload: {
						url: '',
						fresh: false,
					}
				})
			}
		});
	};

	handleUploadChange = (file, fileList) => {
		let reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => {
			this.setState({
				upload: {
					url: reader.result,
					fresh: true,
				},
			});
		}
	};

	render() {
		const { form, itemList, isDialog, dialogConfig } = this.props;
		const { upload } = this.state;
		const { getFieldDecorator } = form;
		const formItemLayout = {
			labelCol: {
				xs: {
					span: 24
				},
				sm: {
					span: 6
				},
			},
			wrapperCol: {
				xs: {
					span: 24
				},
				sm: {
					span: 16
				},
			},
		};

		const wrapperCol = {
			span: 24
		}

		let vm = this;
		const uploadProps = {
			name: 'file',
			headers: {
				Authorization: buildAuthorization(),
			},
			onChange(info) {
				const status = info.file.status;
				if (status !== 'uploading') {}
				if (status === 'done') {
					message.success(`${info.file.name} 图片上传成功.`);
				} else if (status === 'error') {
					message.error(`${info.file.name} 图片上传失败.`);
					vm.setState({
						upload: {
							url: '',
							fresh: false,
						}
					});
				}
			},
		};

		const renderFormItem = (items) => {
			let itemComponent = null;
			switch (items.type) {
				case 'input':
					itemComponent = (
						<Col {...wrapperCol} key={items.value} style={{whiteSpace: 'nowrap'}}>
						{
							!items.hide ? 
							<FormItem {...formItemLayout} label={items.label}>
								{getFieldDecorator(items.value, {
									rules: [items.rules],
									initialValue: items.initialValue,
								})(
									<Input placeholder={items.placeholder} onChange={items.onChange}/>
								)}
							</FormItem>
							: ''
						}
						</Col>
					);
					break;
				case 'select':
					const optionItems = items.selectOption ? items.selectOption.map((item) =>
						<Option value={item.value} key={item.value}>{item.label}</Option>			
					) : '';
					itemComponent = (
						<Col {...wrapperCol} key={items.value} style={{whiteSpace: 'nowrap'}}>
						{
							!items.hide ? 
							<FormItem {...formItemLayout} label={items.label}>
								{getFieldDecorator(items.value, {
									rules: [items.rules],
									initialValue: items.initialValue,
								})(
								<Select style={{ width: items.width ? items.width : '100%' }} placeholder={items.placeholder} onChange={items.onChange}>
									{ optionItems }
								</Select>
								)}
							</FormItem>
							: ''
						}
						</Col>
					);
					break;
				case 'rangePicker':
					itemComponent = (
						<Col {...wrapperCol} key={items.value} style={{whiteSpace: 'nowrap'}}>
						{
							!items.hide ?
							<FormItem {...formItemLayout} label={items.label}>
								{getFieldDecorator(items.value, {
									rules: [items.rules],
									initialValue: items.initialValue ? items.initialValue : []
								})(
									<RangePicker
										ranges={items.showQuickChoose ? {
											近7天: [moment().subtract(7, 'days'), moment()],
											近14天: [moment().subtract(14, 'days'), moment()],
											近30天: [moment().subtract(30, 'days'), moment()],
										} : {}}
										placeholder={items.placeholder}
										onChange={items.onChange}
									/>
								)}
							</FormItem>
							: ''
						}
						</Col>
					);
					break;
				case 'upload':
					itemComponent = (
						<Col {...wrapperCol} key={items.value} style={{whiteSpace: 'nowrap'}}>
						{
							!items.hide ?
							<FormItem {...formItemLayout} label={items.label}>
								{getFieldDecorator(items.value, {
									rules: [items.rules],
									initialValue: items.initialValue,
								})(
									<Dragger
										{...uploadProps} 
										action={host[env] + items.url}
										showUploadList={items.showUploadList ? true : false} 
										beforeUpload={(file, fileList) => this.handleUploadChange(file, fileList)}
									>
										{(upload.fresh && upload.url) || (!upload.fresh && upload.url && !items.initialValue) ? 
											<img src={upload.url} style={{maxWidth: "100%"}} /> : ( 
												!upload.fresh && items.initialValue ?
											 	<img src={items.initialValue} style={{maxWidth: "100%"}} /> : 
												<div>
													<p className="ant-upload-drag-icon">
														<Icon type="inbox" />
													</p>
													<p className="ant-upload-text">{items.tips}</p>
												</div>
											)
										}
									</Dragger>
								)}
							</FormItem>
							: ''
						}
						</Col>
					);
					break;
				default:
					break;
			}
			return itemComponent;
		}

		return (
			<div>
			{
				isDialog ?
				<Modal
					title={dialogConfig && dialogConfig.title ? dialogConfig.title : '表单'}
					visible={dialogConfig ? dialogConfig.visible : false}
					onOk={this.handleComfirm}
					onCancel={this.handleFormCancel}
				>
					<Row>
						<Col>
							<Form layout={"horizontal"} onSubmit={this.handleComfirm}>
							{
								itemList ? itemList.map(
									items => renderFormItem(items)
								)
								: ''
							}
							</Form>
						</Col>
					</Row>
				</Modal>
				:
				<Row>
					<Col>
						<Form layout={"horizontal"} onSubmit={this.handleComfirm}>
						{
							itemList ? itemList.map(
								items => renderFormItem(items)
							)
							: ''
						}
						</Form>
					</Col>
					<Col style={{textAlign: 'center'}}>
						<Button onClick={this.handleFormCancel}>取消</Button>
						<Button style={{ marginLeft: 16 }} type="primary" onClick={this.handleComfirm}>查询</Button>
					</Col>
				</Row>
			}
			</div>
		);
	}
}